package com.qqtech.qquan.community.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.qqtech.agent.context.AdminPage;
import com.qqtech.core.common.util.JsonUtil;
import com.qqtech.core.common.util.StringUtil;
import com.qqtech.core.common.util.TimeUtil;
import com.qqtech.core.frame.model.PageKit;
import com.qqtech.core.frame.model.PageOrder;
import com.qqtech.core.frame.model.Result;
import com.qqtech.qquan.community.model.CommunityAddr;
import com.qqtech.qquan.community.model.CommunityAddrQuery;
import com.qqtech.qquan.community.model.CommunityAddrVo;
import com.qqtech.qquan.community.service.CommunityAddrService;
import com.qqtech.qquan.sys.controller.BaseAgentController;

@Controller
@RequestMapping(value = "/community/addr")
public class CommunityAddrController extends BaseAgentController {
	
	@Resource
	private CommunityAddrService communityAddrService;
	
	@RequestMapping(value = "/subset/{communityId}/{parentId}", method = RequestMethod.GET)
	public String subset(@PathVariable Integer communityId,@PathVariable Integer parentId) {
		return "/community/communityAddr-subList";
	}

	@RequestMapping(value = "/subset", method = RequestMethod.POST)
	@ResponseBody
	public AdminPage subset(CommunityAddrQuery query, HttpServletRequest request, HttpServletResponse response) {
		AdminPage adminPage = new AdminPage();
		Pageable pageKit = new PageKit(query.getPage(), new PageOrder(Direction.DESC, "id"));
		Page<CommunityAddrVo> page = communityAddrService.queryPageList(query, pageKit);
		adminPage.setRows(page.getContent());
		adminPage.setTotal(page.getNumberOfElements());
		return adminPage;
	}
	
	/**
	 * 层级去更新
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/toAdd/{communityId}/{parentId}",method = RequestMethod.GET)
	public String toAdd(Model model,@PathVariable Integer communityId,@PathVariable Integer parentId) {
		model.addAttribute("parentId", parentId);
		model.addAttribute("communityId", communityId);
		return "/community/communityAddr-add";
	}
	
	/**
	 * 创建成功
	 * 
	 * @return
	 */
	@RequestMapping(value = "/addr/add")
	@ResponseBody
	public Result add(CommunityAddr communityAddr) {
		Result ret = new Result();
		if (communityAddr.getName()!=null&&communityAddr.getName()!="") {
			communityAddrService.insert(communityAddr);
			return ret;
		}
		ret.addErr("请输入分类名称");
		return ret;
	}
	
	@RequestMapping(value = "/addr/su/add", method = RequestMethod.GET)
	public String add(@RequestParam(required = false) Integer parentId,@RequestParam(required = false) Integer communityId,HttpServletRequest request,
			HttpServletResponse response) {
		if(null!=parentId){
			request.setAttribute("parentId", parentId);
		}
		request.setAttribute("communityId", communityId);
		return "/community/communityAddr-add";
	}
	
	@RequestMapping(value = "/addr/tree", method = RequestMethod.POST)
	@ResponseBody
	public Result tree(HttpServletRequest request, HttpServletResponse response) {
		String parentId = request.getParameter("id");
		String communityId = request.getParameter("communityId");
		if(parentId == null){
			parentId = String.valueOf(0);
		}
		List<CommunityAddrVo> list = communityAddrService.queryListByParentId(Integer.valueOf(communityId),Integer.valueOf(parentId));
		List<Map<Object, Object>> tree = new ArrayList<Map<Object, Object>>();
		if (null != list) {
			for (int i = 0; i < list.size(); i++) {
				CommunityAddrVo m = (CommunityAddrVo) list.get(i);
				Map<Object, Object> node = new HashMap<Object, Object>();
				node.put("id", m.getId());
				node.put("text", m.getName());
				node.put("state", "closed");
				node.put("iconCls", "icon-item");
				Map<String, Object> attributes = new HashMap<String, Object>();
				attributes.put("parentId", m.getParentId());
				attributes.put("communityId", m.getCommunityId());
				node.put("attributes", attributes);
				tree.add(node);
			}
		}
		String json = JsonUtil.toJson(tree);
		try {
			response.getWriter().print(json);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	@RequestMapping(value = "/update/{id}", method = RequestMethod.GET)
	public String update(Model model,@PathVariable Integer id, HttpServletRequest request, HttpServletResponse response) {
		CommunityAddrVo communityAddrVo = communityAddrService.getById(id);
		request.setAttribute("communityAddrVo", communityAddrVo);
		if (null != communityAddrVo && null != communityAddrVo.getParentId()) {
			CommunityAddrVo parent = communityAddrService.getById(communityAddrVo.getParentId());
			request.setAttribute("parent", parent);
		}
		return "/community/communityAddr-update";
	}
	
	@RequestMapping(value = "/update", method = RequestMethod.POST)
	@ResponseBody
	public Result doUpdate(CommunityAddrVo communityAddrVo) {
		Result ret = new Result();
		if (communityAddrVo == null) {
			ret.addErr("参数不能为空");
		} else {
			if (StringUtil.isBlank(communityAddrVo.getName())) {
				ret.addErr("请输入分类名称");
			}
		}
		if (ret.checkForm()) {
			CommunityAddr update = new CommunityAddr();
			update.setId(communityAddrVo.getId());
			update.setParentId(communityAddrVo.getParentId());
			update.setName(communityAddrVo.getName().trim());
			update.setUpdAt(TimeUtil.now());
			communityAddrService.updateById(communityAddrVo);
		}
		return ret;
	}
	
	@RequestMapping(value = "/delete/{id}", method = RequestMethod.POST)
	@ResponseBody
   	public Result doDelete(@PathVariable Integer id) {
		Result ret = new Result();
		CommunityAddrVo dbCommunityAddrVo=communityAddrService.getById(id);
		if(dbCommunityAddrVo != null){
			delete(dbCommunityAddrVo.getId(),dbCommunityAddrVo.getCommunityId());
		}
   		return ret;
   	}
	
	@ResponseBody
	public void delete(int id,int communityId){
		List<CommunityAddrVo> list= communityAddrService.queryListByParentId(communityId,id);
		if(list != null && list.size() >0){
			for(CommunityAddrVo communityAddrVo : list){
				delete(communityAddrVo.getId(),communityAddrVo.getCommunityId());
			}
		}
		communityAddrService.deleteById(id);
	}
}
